#include "ac4315.h"

uint8_t crc5_epc(uint8_t *data, uint16_t length)
{
	uint8_t i;
  uint8_t crc = 0x48;  //initial value: 0x48 = 0x09 <<(8-5)
  while(length--)
    {
        crc ^= *data++;        // crc ^= *data; data++;
        for ( i = 0; i < 8; i++ )
        {
            if ( crc & 0x80 )
                crc = (crc << 1) ^ 0x48;        // 0x48 = 0x09<<(8-5)
            else
                crc <<= 1;
        }
    }
    return crc >> 3;
}

//crc compute
void CrcCompute(uint8_t * txbuffer)
{
	uint8_t crc5;
	crc5 = crc5_epc(txbuffer,4);
	txbuffer[2] = (crc5 <<3 ) | txbuffer[2];
}

//counts 1 of binary type
uint16_t bitoneCount(uint16_t n)
{
	uint16_t tmp = n - ((n >> 1) & 0133333) - ((n >> 2) & 0111111);
  return ((tmp + (tmp >> 3)) & 0070707) % 63;
}


//ecc data encode
uint16_t dataEncode(uint16_t n)
{
    uint8_t i;
    uint8_t ham_code;
    uint16_t temp1,temp2;
    uint16_t data_encode,ded;

    ham_code = 0;
    temp1 = ((n << 5) & 0xFE00) | ((n & 0x000E) << 4) | ((n & 0x0001) << 3);

    for (i = 0; i < 16; i++)
    {
        if (temp1 & (1 << i))
        {
            ham_code = ham_code ^ i;
        }
    }

    temp2 = (temp1 & ~(0x0113)) | (ham_code & 1) << 1| (ham_code & 2) << 1 | (ham_code & 4) << 2 | (ham_code & 8) << 5;

    ded = (bitoneCount(temp2) % 2) ? 1 : 0;

    data_encode = n | (ham_code << 12) | ded << 11;

    return data_encode;
}
